<?php
/**
 * XuYuan Project
 *
 * @package	XueYuan 
 * @author	Jiuchi Team
 * @since	Version 1.0.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * User controller class
 * @author Wayne Yu
 */
class Login extends CI_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->library('session');
		$this->load->library('apioutput');
		$this->load->library('msgblock');
		$this->load->helper('url');
		$this->load->model('user_model');
	}
	
	/**
	 * Login action of this controller
	 */
	public function index(){
		$tick = md5(time());
		 
		$this->session->set_flashdata('login_tick', $tick);
		$data = array(
				'tick'=>$tick
		);
		//load view
		$this->load->view('login/login',$data);
	}
	
	/**
	 * Register
	 */
	public function register(){
		//get post data
		$input = $this->input->post();
		//check the data
		$ticket = $input['ticket'];
		$storeTicket = $this->session->userdata('register_tick');
		if($ticket != $storeTicket){
			$this->msgblock->addError('验证失败,请稍后重试');
			redirect(site_url('login'));
			return;
		}
		if(empty($input['telephone']) || !preg_match('/^(13|15|18)[0-9]{9}$/',$input['telephone'])){
			$this->msgblock->addError('手机号码非法，请重新输入');
			redirect(site_url('login'));
			return;
		}
		$resAccount = $this->user_model->getUserByAccount($input['telephone']);
		if($resAccount != FALSE){
			$this->msgblock->addError('您输入的手机号已被注册！');
			redirect(site_url('login'));
			return;
		}
		//check the verify code
		if($this->apioutput->getAuthCode($input['telephone'], 'Reg') != $input['authcode']){
			$this->msgblock->addError($this->apioutput->getAuthCode($input['telephone'], 'Reg').'您输入手机验证码有误！');
			redirect(site_url('login'));
			return;
		}
		if(empty($input['password']) || strlen($input['password']) < 6){
			$this->msgblock->addError('密码必须大于六位！');
			redirect(site_url('login'));
			return;
		}

		
		$userData['telephone']	= $input['telephone'];
		$userData['nickname']	= $input['telephone'];
		$userData['salt']		= substr(uniqid(rand()), -6);
		$userData['password']	= md5(md5($input['password']).$userData['salt']);

		$this->user_model->begin();
		$uid = $this->user_model->createEntity($userData);
		if($uid <= 0){
			$this->user_model->rollback();
			$this->msgblock->addError('系统忙，请稍后重试！');
			redirect(site_url('login'));
			return;
		}
		$this->user_model->commit();
		
		//page redirect
			
		$this->session->set_userdata(array(
			'uid'		=> $uid,
			'telephone'	=> $userData['telephone'],
			'nickname'	=> $userData['nickname'],
			'avatar'	=> '/assets/images/default-avatar.jpg'
		));

		$this->msgblock->addSuccess('恭喜您，注册成功！');
		redirect('mycenter');
	}
	
	/**
	 * 
	 */
	public function loginPost(){
		$ret_tick = $this->input->post('login_tick');
		$account = $this->input->post('account');//获得登入用户
		$pwd = $this->input->post('password');//获得用户密码
		$ret = $this->_login($account, $pwd, $ret_tick);
		if($ret == true){
			redirect(site_url('home/msg'));
			return;
		}else{
			$this->msgblock->addError('您输入的用户名或密码错误,请重试');
			redirect(site_url('login'));
			return;
		}
	}
	
	/**
	 * Logout
	 */
	public function logout(){
		$uid = $this->session->userdata('uid');
		if(!empty($uid)){
			$this->session->unset_userdata('uid');
			$this->session->unset_userdata('telephone');
			$this->session->unset_userdata('nickname');
			session_destroy();
			session_start();
		}
		redirect(site_url('login'));
	}

	/**
	 * Get the verify code image
	 */
	public function verifyCode(){
		//generate the verify code
		$sourceStr = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";
		mt_srand();
		$verifyCode = "";
		for ($i = 0; $i < 4; $i++) {
			$verifyCode .= $sourceStr[mt_rand(0, 33)];
		}
		
		//set the image size and image
		@ header("Content-Type:image/png");
		$im = imagecreate(55, 25);
		$back = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
		$pix  = imagecolorallocate($im, 187, 230, 247);
		$line = imagecolorallocate($im, 90, 185, 255);
		$font = imagecolorallocate($im, 41, 163, 238);
		
		//Draw some spots and lines
		mt_srand();
		for($i = 0; $i < 1000; $i++){
			imagesetpixel($im, mt_rand(0, 94), mt_rand(0, 40), $pix);
		}
		for($i = 0; $i < 10; $i++){
			imageline($im, mt_rand(0, 94), mt_rand(0, 40), mt_rand(0, 94),  mt_rand(0, 40), $line);
		}
		
		//Draw the verify code
		imagestring($im, 5, 10, 5, $verifyCode, $font);
		
		//Draw the rectangle and output the image
		imagerectangle($im, 0, 0, 54, 24, $font);
		imagepng($im);
		imagedestroy($im);
		//Store the verify code to session
		$this->session->set_flashdata('verify_code', $verifyCode);
		$verifyCode = $this->session->flashdata('login_tick');
		$this->session->set_flashdata('login_tick', $verifyCode);
		//set cookie
		SetCookie("verification", $verifyCode, time() + 7200, "/");
		
// 		$tick = $this->session->flashdata('login_tick');
// 		$this->session->set_flashdata('login_tick', $tick);
	}
	
	/**
	 * Check the login parms and login
	 * @param string $account
	 * @param string $pwd
	 * @param string $tick
	 * @return boolean
	 */
	private function _login($account, $pwd, $tick){
		$sess_tick = $this->session->flashdata('login_tick');
		if($sess_tick != $tick){
			return false;
		}
		$usrInfo = $this->user_model->getUserByAccount($account);
		if(empty($usrInfo) || $usrInfo['password'] != md5(md5($pwd).$usrInfo['salt'])){
			return false;
		}
		 
		$ip = $this->input->ip_address();
		 
		$upinfo = array('lastip'=>$ip, 'lastlogined_at'=>date('Y-m-d H:i:s', time()));
		$res = $this->user_model->updateInfo($usrInfo['id'],$upinfo);
		if(!$res){
			return false;
		}

		//update session
		$this->session->set_userdata('uid', $usrInfo['id']);
		$this->session->set_userdata('telephone', $usrInfo['telephone']);
		$this->session->set_userdata('nickname', $usrInfo['nickname']);
		$this->session->set_userdata('avatar', $usrInfo['headportrait']);
		return true;
	}
	
	/**
	 * Check if the telephone is registered
	 */
	public function checkAccount(){
		$account = $this->input->post('Telephone');
		$resAccount = $this->user_model->getUserByAccount($account);
		$verifyCode = $this->session->flashdata('verify_code');
		$this->session->set_flashdata('verify_code', $verifyCode);
		$verifyCode = $this->session->flashdata('login_ticket');
		$this->session->set_flashdata('login_ticket', $verifyCode);
		if($resAccount != FALSE){
			$this->apioutput->apiResponseError('您输入的手机号已被注册！');
		} else{
			$this->apioutput->apiResponseSuccess();
		}
	}
	
	/**
	 * 
	 */
	public function getAuthCode(){
		//initialiazation
		$input = $this->input->post();
		if(empty($input['Telephone'])){
			$this->apioutput->apiResponseError('手机号码不能为空，请重新输入');
		}
		if(!preg_match('/^(13|15|18)[0-9]{9}$/',$input['Telephone'])){
			$this->apioutput->apiResponseError('手机号码非法，请重新输入');
		}
		if(!in_array($input['Type'], array('Reg', 'Pwd'))){
			$this->apioutput->apiResponseError('参数类型不正确，请重新输入');
		}
		 
		//业务逻辑
		switch ($input['Type']){
			case 'Reg':
				$count = 1;
				$ret = $this->user_model->retrieve($count, NULL, NULL, NULL, array('telephone'=>$input['Telephone']));
				if($ret != 0) {
					$this->apioutput->apiResponseError('您输入的手机号已存在！');
				}
				break;
			case 'Pwd':
				$count = 1;
				$ret = $this->user_model->retrieve($count, NULL, NULL, NULL, array('telephone'=>$input['Telephone']));
				if($ret != 1) {
					$this->apioutput->apiResponseError('您输入的手机号不存在！');
				}
				break;
			default:
				$this->apioutput->apiResponseError('错误的消息类型！');
		}
		 
		//
		$code = '123456';//substr(uniqid(rand()), -6);
		$count = $this->apioutput->setAuthCode($input['Telephone'],$input['Type'],$code);
		$tick = md5(time());
		$this->session->set_userdata('register_tick', $tick);
		if($count > 7) {
			$this->apioutput->apiResponseError($count.'请求过于频繁');
		}
		//call the message platform

		//output
		$this->apioutput->apiResponseSuccess($tick);
	}
	
	/**
	 * Check the Auth code
	 */
	public function checkCaptcha(){
		$verify_code = $this->input->post('Captcha');
		$vcode = $this->session->flashdata('verify_code');
		if($vcode != strtoupper($verify_code)){
			$this->apioutput->apiResponseError($verify_code.'您输入的验证码有误，请重试'.$vcode);
		} else{
			$this->apioutput->apiResponseSuccess();
		}
	}
}